package org.practice.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.practice.action.vo.CartItemVO;
import org.practice.model.User;
import org.practice.service.CartService;
import org.practice.service.bo.CartBO;
import org.practice.util.Constant;
import org.practice.util.CookieUtil;
import org.practice.util.ShopServiceFactory;

@SuppressWarnings("serial")
public class CartAction extends BaseAction {
	private CartItemVO cartItemVO=new CartItemVO();
	private CartService service=ShopServiceFactory.createCartService();
	
	public String show() throws Exception{
		CartBO cart=getCart();
		service.countEffectiveCartItems(cart);
		service.countDropCartItems(cart);
		service.calculateTotalPrice(cart);
		service.calculateDangPrice(cart);
		if (service.isEmpty(cart)) {
			this.addActionMessage(getText("error.cart.empty"));
		}
		return SUCCESS;
	}

	public String add()throws Exception {
		CartBO cart=getCart();
		service.addCartItem(cart,cartItemVO.getProductId());
		saveToCookie(cart);
		return SUCCESS;
	}

	public String update()throws Exception {
		CartBO cart=getCart();
		service.calculateTotalPrice(cart);
		service.calculateDangPrice(cart);
		service.updateNum(cart,cartItemVO.getProductId(), cartItemVO.getNum());
		saveToCookie(cart);
		return SUCCESS;
	}

	public String drop()throws Exception {
		CartBO cart=getCart();
		service.drop(cart,cartItemVO.getProductId());
		saveToCookie(cart);
		return SUCCESS;
	}

	public String recovery()throws Exception {
		CartBO cart=getCart();
		service.recovery(cart,cartItemVO.getProductId());
		saveToCookie(cart);
		return SUCCESS;
	}

	private CartBO getCart() throws Exception {
		HttpSession session = getSession();
		User user = (User) session.getAttribute(Constant.SESSION_KEY_USER);
		CartBO cart = (CartBO) session.getAttribute(Constant.SESSION_KEY_CART);
		if (cart == null) {
			cart = new CartBO(user.getId());
			String cartCookieVal = CookieUtil.findCookie(getRequest(),Constant.COOKIE_KEY_CARTID);
			if (cartCookieVal != null) {
				service.load(cart,cartCookieVal);
			}
			session.setAttribute(Constant.SESSION_KEY_CART, cart);
		}
		return cart;
	}

	private void saveToCookie(CartBO cart)
			throws Exception {
		CookieUtil.addCookie(getResponse(), Constant.COOKIE_KEY_CARTID, service.generateSerialize(cart));
	}

	public CartItemVO getCartItemVO() {
		return cartItemVO;
	}

	public void setCartItemVO(CartItemVO cartItemVO) {
		this.cartItemVO = cartItemVO;
	}
	
}
